package com.ccp.dev.qbdms.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.TimeUtil;
import com.ccp.dev.qbdms.expimp.annotation.FlowSubject;
import com.ccp.dev.qbdms.expimp.annotation.ImpAnnotation;
import com.ccp.dev.qbdms.model.Commonality;
import com.ccp.dev.qbdms.model.SysReportMaster;
import com.ccp.dev.qbdms.service.CommonalityService;
import com.ccp.dev.qbdms.service.SysReportMasterService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.webservice.cxf.CxfClient;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/qbdms/commonality")
@Controller
public class CommonalityController extends SysBaseController {

    @Resource
    private ProcessRunService processRunService;
    @Resource
    private CommonalityService commonalityService;
    @Resource
    private SysReportMasterService sysReportMasterService;
    @Value(value = "${service.customProcessName}")
    private boolean customProcessName = true;
    /**
     * 信息上报
     * @param request
     * @param commonality
     * @return
     */
    @PostMapping("/report")
    @ResponseBody
    @Action(description="上报信息")
    public Object reportData(HttpServletRequest request, Commonality commonality){
        //根据系统属性进行判断流程上报或状态位上报
        if(PropertyUtil.getBooleanByAlias("flow_report")){
            //流程启动
            SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
            ProcessCmd processCmd = new ProcessCmd();
            processCmd.setProcDefId(commonality.getProcDefId());
            //流程Key
            Map<String,Object> map = new HashMap<>();
            map.put("className",commonality.getClassName());
            processCmd.setVariables(map);
            processCmd.setModelKey(commonality.getModelKey());
            processCmd.setUserAccount(sysUser.getAccount());
            if(customProcessName){
                try {
                    //添加流程变量,修改流程标题
                    String className = StringUtil.convertToCamelCase(commonality.getTableName());
                    className = CxfClient.getClassName(className);
                    String end = "";
                    if(BaseUtil.isPlantLevel()){
                        end = " - 所报院 - " + TimeUtil.formatTime(System.currentTimeMillis());
                    }else if(BaseUtil.isHospitalLevel()){
                        end = " - 院报集团 - " + TimeUtil.formatTime(System.currentTimeMillis());
                    }
                    Class<?> clazz1 = Class.forName("com.ccp.dev.qbdms.model." + className);
                    FlowSubject clsAnnotation = clazz1.getAnnotation(FlowSubject.class);
                    String description = "";
                    if(null != clsAnnotation && StringUtil.isNotEmpty(clsAnnotation.subjectName())){
                        description = clsAnnotation.subjectName();
                    }else{
                        description = clazz1.getSimpleName();
                    }
                    description += end;
                    processCmd.setSubject(description);
                } catch (Exception e) {
                    processCmd.setSubject("");
                    e.printStackTrace();
                }
            }
            try {
                if(!(commonalityService.executable(commonality))){
                    return getResultDataError(commonalityService.returnMsg(commonality.isRepeatReporting()));
                }

                //在自定义上报流程表中添加上报数据信息
                String genId = ProjectUUIDUtils.getUUIDFor32();
                //启动流程
                processCmd.setBusinessKey(genId);
                processRunService.startProcess(processCmd);

                SysReportMaster sysReportMaster = new SysReportMaster();
                sysReportMaster.setId(genId);
                sysReportMaster.setTableName(commonality.getTableName());
                sysReportMaster.setCreateTime(new Date());
                sysReportMaster.setClassName(commonality.getClassName());
                sysReportMasterService.saveReportMaster(sysReportMaster,commonality.getDataId());
                return getResultDataSuccess("flow.start.success");
            } catch (Exception e) {
                e.printStackTrace();
                return getResultDataError("flow.start.failure");
            }
        }else{
            String returnMsg = commonalityService.report(commonality);
            if("operation.success".equals(returnMsg)){
                return getResultDataSuccess(returnMsg);
            }else{
                return getResultDataError(returnMsg);
            }
        }

    }

    /**
     * 无需上报
     * @param request
     * @param dataId 业务数据主键
     * @param tableName 表名
     * @return
     */
    @PostMapping("/doNotNeedReport")
    @ResponseBody
    @Action(description = "无需上报")
    public Object doNotNeedReport(HttpServletRequest request,@RequestParam("dataId") String dataId,@RequestParam("tableName") String tableName,@RequestParam("className")String className){
        String returnMsg = commonalityService.doNotNeedReport(tableName,dataId.split(","),className);
        if("operation.success".equals(returnMsg)){
            return getResultDataSuccess(returnMsg);
        }else{
            return getResultDataError(returnMsg);
        }
    }

    /**
     * 退回待修改
     * @param request
     * @param dataId 业务数据主键
     * @param tableName 表名
     * @return
     */
    @PostMapping("/returnAndUpdate")
    @ResponseBody
    @Action(description = "退回待修改")
    public Object returnAndUpdate(HttpServletRequest request,@RequestParam("dataId") String dataId,@RequestParam("tableName") String tableName,@RequestParam("returnMsg") String returnMsg,@RequestParam("className")String className){
        String operationMsg = commonalityService.returnAndUpdate(tableName,dataId.split(","),returnMsg,className);
        if("operation.success".equals(operationMsg)){
            return getResultDataSuccess(operationMsg);
        }else{
            return getResultDataError(operationMsg);
        }
    }

    /**
     * 发起流程后跳转reportList页面
     * @param request
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/reportList")
    @Action(description="跳转到质量问题管理首页", exectype = "页面跳转日志")
    public String viewReportList(HttpServletRequest request,@RequestParam("id")String id,ModelMap modelMap) {
        modelMap.put("dataId",id);
        String className = sysReportMasterService.getClassNameById(id);
        String viewReportList = className + "/reportList";
        return viewReportList;
    }
}
